import {useEffect, useState, useRef} from "react";

function useCallbackState (initialState) {
    const [state, setState] = useState(initialState);
  const callbackRef = useRef(null);

  const setStateWithCallback = (newState, callback) => {
    callbackRef.current = callback;
    setState(prev => typeof newState === 'function' ? newState(prev) : newState);
  };

  useEffect(() => {
    console.table("useCallbackState", state)
    if (callbackRef.current) {
      callbackRef.current(state);
      callbackRef.current = null; // 执行后清除回调
    }
  }, [state]);

  return [state, setStateWithCallback];


  // const cbRef = useRef();
  // const [data, setData] = useState(od);

  // useEffect(() => {
  //   console.log(data)
  //   if(cbRef.current) {
  //     cbRef.current(data)
  //     cbRef.current = null
  //   }
  // }, [data]);

  // return [data, function (d, callback) {
  //   cbRef.current = callback;
  //   setData(d);
  // }];
}

export {useCallbackState};
